package com.gun3y.entity.htmlparser;

import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Tag;
import org.htmlparser.Text;

import com.gun3y.entity.pattern.ExpressionType;

/**
 * @author c66117
 * 
 *         tag name value filter
 * 
 */
public class TagNameExFilter implements NodeFilter {

    private static final long serialVersionUID = -5222117985754619553L;

    protected String tagName;

    protected String tagValue;

    protected ExpressionType tagExpression = ExpressionType.ExactMatch;

    public boolean accept(Node paramNode) {
	String testStr = "";

	if (paramNode instanceof Text && StringUtils.isBlank(this.tagName)) {
	    testStr = ((Text) paramNode).getText();
	}
	else if (paramNode instanceof Tag && !((Tag) paramNode).isEndTag() && ((Tag) paramNode).getTagName().equalsIgnoreCase(this.tagName)) {
	    testStr = ((Tag) paramNode).toPlainTextString();
	    if (StringUtils.isBlank(this.tagValue)) {
		return true;
	    }
	}
	else {
	    return false;
	}

	testStr = testStr.trim();
	return this.tagExpression.isValid(testStr, this.tagValue);
    }

    public String getTagName() {
	return this.tagName;
    }

    public void setTagName(String tagName) {
	if (tagName != null) {
	    this.tagName = tagName.toUpperCase(Locale.ENGLISH);
	}
	else {
	    this.tagName = StringUtils.EMPTY;
	}
    }

    public String getTagValue() {
	return tagValue;
    }

    public void setTagValue(String tagValue) {
	this.tagValue = tagValue;
    }

    public ExpressionType getTagExpression() {
	return tagExpression;
    }

    public void setTagExpression(ExpressionType tagExpression) {
	if (tagExpression != null) {
	    this.tagExpression = tagExpression;
	}
	else {
	    this.tagExpression = ExpressionType.ExactMatch;
	}
    }

    public TagNameExFilter() {
	super();
    }

    public TagNameExFilter(String tagName) {
	super();
	this.tagName = tagName;
    }

    public TagNameExFilter(String tagName, String tagValue, ExpressionType tagExpression) {
	super();
	this.tagName = tagName;
	this.tagValue = tagValue;
	this.tagExpression = tagExpression;
    }

}
